package com.xebest.web.controller.order;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.xebest.api.util.OpertorLogUtil;
import com.xebest.common.base.controller.BASEMessage;
import com.xebest.common.base.controller.BaseController;
import com.xebest.common.base.controller.BaseResponse;
import com.xebest.common.enums.logtype.ErpLogTypeEnum;
import com.xebest.common.util.HttpClientUtil;
import com.xebest.common.util.XeBaseUtil;
import com.xebest.config.SmsConfig;
import com.xebest.constant.XeConstans;
import com.xebest.constant.XeSmsConstans;
import com.xebest.util.DateUtil;
import com.xebest.util.RequestUtil;
import com.xebest.util.SmsConstants;
import com.xebest.util.SysSetBeanUtils;
import com.xebest.util.msg.XeVenOrderMsg;
import com.xebest.web.form.XeVenInquirySheetForm;
import com.xebest.web.model.base.XePageInfo;
import com.xebest.web.service.XeVenInquirysheetService;
import com.xebest.web.service.XeVenProSkuService;
import com.xebest.web.view.ErpUserInfo;
import com.xebest.web.view.XeVenInquirySheetView;
import com.xebest.web.view.XeVenProView;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("xeVenInquirySheet")
@Scope("prototype")
public class XeVenInquirySheetController extends BaseController {

    //日志记录类
    private static final Logger log = LoggerFactory.getLogger(XeVenInquirySheetController.class);

    @Autowired
    private XeVenInquirysheetService xeVenInquirysheetService;   //询价单业务操作.
    @Autowired
    private XeVenProSkuService xeVenProSkuService;
    @Autowired
    private SmsConfig smsConfig;

    /**
     * 询价单列表
     *
     * @auther wangyp
     */
    @RequestMapping("queryXeVenInquirySheetList")
    public @ResponseBody
    BaseResponse queryXeVenInquirySheetList(@RequestBody XeVenInquirySheetForm form) {
        log.info("询价单列表入参:" + JSONArray.toJSON(form));
        //验证参数
        if (StringUtils.isBlank(form.getCreateDateStart()) && StringUtils.isNotBlank(form.getCreateDateEnd())) {
            String time = DateUtil.strToNMonth(form.getCreateDateEnd(), -3);
            form.setCreateDateStart(time);
        }
        if (StringUtils.isBlank(form.getCreateDateStart()) && StringUtils.isBlank(form.getCreateDateEnd())) {
            form.setCreateDateEnd(DateUtil.getDate(new Date()));
            form.setCreateDateStart(DateUtil.strToNMonth(form.getCreateDateEnd(), -3));
        }
        if (StringUtils.isBlank(form.getCreateDateEnd()) && StringUtils.isNotBlank(form.getCreateDateStart())) {
            String time = DateUtil.strToNMonth(form.getCreateDateStart(), 3);
            form.setCreateDateEnd(time);
        }
        if (StringUtils.isNotBlank(form.getCreateDateStart()) && StringUtils.isNotBlank(form.getCreateDateEnd())) {
            boolean flag = DateUtil.comparableTime(form.getCreateDateStart(), form.getCreateDateEnd());
            if (!flag) {
                return sendAjaxError(BASEMessage.PARAM_ERROR, XeVenOrderMsg.TIME_MSG);
            }
        }
        //拼装参数
        XePageInfo<XeVenInquirySheetView> xePageInfo;
        PageHelper.startPage(form.getPageNum(), form.getPageSize(), true);
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        form.setUserCode(userInfo.getUserCode());
        setOrderTime(form);
        //输出结果
        List<XeVenInquirySheetView> inquirySheetList = this.xeVenInquirysheetService.queryXeVenInquirySheetList(form);
        try {
            xePageInfo = new XePageInfo<XeVenInquirySheetView>(inquirySheetList);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("inquirySheetList", inquirySheetList);
            map.put("xePageInfo", xePageInfo);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("询价单查询List异常：{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 设置查询时间
     */
    private void setOrderTime(XeVenInquirySheetForm form) {
        if (null != form.getSearchType()) {
            switch (form.getSearchType()) {
                case 1:
                    break;
                case 2:
                    form.setProductName(form.getInquirysheetCode());
                    form.setInquirysheetCode(null);
                    break;
                case 3:
                    form.setProductSku(form.getInquirysheetCode());
                    form.setInquirysheetCode(null);
                    break;
                case 4:
                    form.setPurchName(form.getInquirysheetCode());
                    form.setInquirysheetCode(null);
                    break;
                case 5:
                    form.setConName(form.getInquirysheetCode());
                    form.setInquirysheetCode(null);
                    break;
                default:
                    break;
            }
        }
        if (null != form.getSearchTimeType()) {
            switch (form.getSearchTimeType()) {
                case 1:
                    break;
                case 2:
                    form.setPriceDateStart(form.getCreateDateStart());
                    form.setPriceDateEnd(form.getCreateDateEnd());
                    form.setCreateDateStart(null);
                    form.setCreateDateEnd(null);
                    break;
                case 3:
                    form.setDeadDateStart(form.getCreateDateStart());
                    form.setDeadDateEnd(form.getCreateDateEnd());
                    form.setCreateDateStart(null);
                    form.setCreateDateEnd(null);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 询价单成交
     *
     * @auther wangyp
     */
    @RequestMapping("updateInquirySheetDeal")
    public @ResponseBody
    BaseResponse updateInquirySheetDeal(@RequestBody XeVenInquirySheetForm form) {
        log.info("询价单成交入参" + JSONArray.toJSONString(form));
        try {
            //验证参数
            if (StringUtils.isBlank(form.getAgreePrice().toString())
                    || StringUtils.isBlank(form.getInquirysheetCode())) {
                return sendAjaxError(BASEMessage.PARAM_ERROR);
            }
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
            //修改成交价
            int result = xeVenInquirysheetService.updateSheetDeal(form, userInfo);
            if (result == XeConstans._XE_ONE) {
                //根据询价单号查询询价信息
                XeVenInquirySheetView view = xeVenInquirysheetService.listXeVenInquiryByCode(form.getInquirysheetCode());
                //查询商品失效时间
                XeVenProView skuView = xeVenProSkuService.selectFailureTimeByProSku(view.getProductSku());
                //询价单同意报价发送短信
                StringBuffer sb = new StringBuffer();
                sb.append("mobileNO=").append(view.getConPhone()).append("&merchantKey=")
                        .append(smsConfig.getMerchantKey());
                String verifyString = XeBaseUtil.baseUtil.getKeyedDigest(
                        sb.toString(), SmsConstants.MSG_MERCHANT_KEY);
                JSONObject smsJson = new JSONObject();
                smsJson.put("userName", view.getPurchName());
                smsJson.put("mobileNO", view.getConPhone());
                smsJson.put("vendorName", view.getOperUser());
                smsJson.put("orderNum", view.getInquirysheetCode());
                smsJson.put("sendSource", "询价单同意报价发送短信");
                smsJson.put("smsNO", XeSmsConstans.XE_INQU_AGREE);
                smsJson.put("verifyString", verifyString);
                smsJson.put("Num", skuView.getFailureTime());
                smsJson.put("money", view.getAgreePrice());
                String send = HttpClientUtil.postJSON(smsConfig.getSmsUrl(), smsJson);
                log.info("返回信息{}", JSONObject.toJSONString(send));
                //添加操作日志
                String ipAddress = RequestUtil.getClientIpAddress(request);
                String logType = ErpLogTypeEnum.erpInquirySheetAgree.getValue();
                StringBuffer operatorContent = new StringBuffer();
                String userCode = userInfo.getUserCode();
                String userName = userInfo.getUserName();
                operatorContent.append("商户" + "【" + userCode + "】" + "对询价单" + form.getInquirysheetCode()
                        + "进行报价操作，报价:" + form.getAgreePrice() + "元");
                OpertorLogUtil.opertorLog.sendOperatorLogByParam(ipAddress, form.getInquirysheetCode(), logType, userName, operatorContent.toString(), userCode);


                return sendAjaxOK();
            } else {
                return sendAjaxError();
            }
        } catch (Exception e) {
            log.error("询价单成交异常：{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 询价单取消
     *
     * @auther wangyp
     */
    @RequestMapping("updateInquirySheetCancel")
    public @ResponseBody
    BaseResponse updateInquirySheetCancel(@RequestBody XeVenInquirySheetForm form) {
        log.info("询价单驳回入参" + JSONArray.toJSONString(form));
        try {
            //验证参数
            if (StringUtils.isBlank(form.getInquirysheetCode())
                    || StringUtils.isBlank(form.getRemark())) {
                return sendAjaxError(BASEMessage.PARAM_ERROR);
            }
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
            //询价单驳回
            int result = xeVenInquirysheetService.updateSheetCancel(form, userInfo);
            if (result == XeConstans._XE_ONE) {
                //根据询价单号查询询价信息
                XeVenInquirySheetView view = xeVenInquirysheetService.listXeVenInquiryByCode(form.getInquirysheetCode());
                //询价单同意报价发送短信
                StringBuffer sb = new StringBuffer();
                sb.append("mobileNO=").append(view.getConPhone()).append("&merchantKey=")
                        .append(smsConfig.getMerchantKey());
                String verifyString = XeBaseUtil.baseUtil.getKeyedDigest(
                        sb.toString(), SmsConstants.MSG_MERCHANT_KEY);
                JSONObject smsJson = new JSONObject();
                smsJson.put("userName", view.getPurchName());
                smsJson.put("mobileNO", view.getConPhone());
                smsJson.put("vendorName", view.getOperUser());
                smsJson.put("orderNum", view.getInquirysheetCode());
                smsJson.put("sendSource", "询价单驳回发送短信");
                smsJson.put("smsNO", XeSmsConstans.XE_INQU_BOHUI);
                smsJson.put("verifyString", verifyString);
                String send = HttpClientUtil.postJSON(smsConfig.getSmsUrl(), smsJson);
                log.info("返回信息{}", JSONObject.toJSONString(send));
                //添加操作日志
                String ipAddress = RequestUtil.getClientIpAddress(request);
                String logType = ErpLogTypeEnum.erpInquirySheetBoHui.getValue();
                StringBuffer operatorContent = new StringBuffer();
                String userCode = userInfo.getUserCode();
                String userName = userInfo.getUserName();
                operatorContent.append("商户" + "【" + userCode + "】" + "对询价单" + form.getInquirysheetCode()
                        + "进行驳回操作，驳回原因:" + form.getRemark());
                OpertorLogUtil.opertorLog.sendOperatorLogByParam(ipAddress, form.getInquirysheetCode(), logType, userName, operatorContent.toString(), userCode);

                return sendAjaxOK();
            } else {
                return sendAjaxError();
            }
        } catch (Exception e) {
            log.error("询价单取消异常：{}", e);
            return sendAjaxError();
        }
    }

}
